<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" size="medium"
      @click="$router.push('/sys-admin/serve/banner/add-new')">添加轮播图</el-button>
      <el-select v-model="typeId" clearable placeholder="请选择类别" style="margin-left: 20px" @change="changeLoad">
        <el-option
            v-for="item in typeListOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column label="图片" width="200" header-align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="scope.row.url" alt="" style="width: 600px;">
            <img slot="reference" :src="scope.row.url" style="width: 100%;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="alt" label="备注" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="120" align="center"></el-table-column>
      <el-table-column label="是否显示" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.isDisplay"
              active-color="#13ce66"
              inactive-color="#999"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <!--<el-table-column label="查看图片" width="100" align="center">
        <el-button size="small">查看</el-button>
      </el-table-column>-->
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-edit" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px auto;text-align: right;">
      <el-pagination
          @current-change="changePageNum"
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage">
      </el-pagination>
    </div>

    <el-dialog title="编辑轮播图" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">

        <el-form-item label="轮播图">
          <div class="picture-list">
            <el-upload
                name="imageFile"
                class="picture-uploader"
                :action="uploadBanner"
                :show-file-list="false"
                :on-success="handleUploadSuccess">
              <i class="el-icon-upload picture-uploader-icon"></i>
              <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
              <div class="picture-uploader-text">仅允许上传不超过 <i>5MB</i> 的图片</div>
            </el-upload>
            <div class="picture-item">
              <el-image class="image"
                        :src="editForm.url" fit="cover"></el-image>
            </div>
          </div>
        </el-form-item>


        <el-form-item label="简介" prop="title">
          <el-input v-model="editForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="alt">
          <el-input v-model="editForm.alt" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="轮播图类别" prop="typeId">
          <el-select v-model="editForm.typeId" placeholder="请选择">
            <el-option
                v-for="item in typeListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import global from '../../../Global'
let preBannerUrl = global.preBanners;
let preResourceUrl = global.preResources ;
export default {
  data() {
    return {
      uploadBanner: preResourceUrl+'/upload/image/banner',
      typeListOptions: [{id:1, name:'往期回顾'}, {id:2, name:'名模佳丽'}],
      typeId: '',
      value: '0',
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      dialogFormVisible: false,
      editForm: {
        id: '',
        url: '',
        title: '',
        alt: '',
        sort: '',
        typeId: '',
        isDisplay: ''
      },
      rules: {
        url: [
          { required: true, message: '请上传轮播图', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    toggleEnable(banner){

    },
    //修改Dialog
    openEditDialog(banner){
      let url = preBannerUrl + "/"+ banner.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
            'headers': {
              'Authorization': localJwt
            }
          }).get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBannerList();
            }
          });
        }
      });
    },
    submitEditForm(){
      let url = preBannerUrl + "/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
            'headers': {
              'Authorization': localJwt
            }
          }).post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify({
            title: '提示',
            message: '编辑轮播图成功！'
          });
          this.dialogFormVisible = false;
          this.loadBannerList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadBannerList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //头像上传成功
    handleUploadSuccess(response){
      this.editForm.oldUrl =  this.editForm.url;
      this.editForm.url = response.data.url;

      let url = preBannerUrl + "/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.handleDeletePicture();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadBannerList();
            }
          });
        }else {
          this.$alert(jsonResult.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //物理删除服务器保存头像
    handleDeletePicture(){
      if(this.editForm.oldUrl == ''){
        return;
      }
      let url = preResourceUrl + "/remove/image/banner";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          console.log("图片物理删除成功!");
        }else{
          console.log("图片物理删除失败!");
        }
      });
    },
    //删除提示
    openDeleteConfirm(banner) {
      this.$confirm('此操作将永久删除【 ' + banner.id + '-' + banner.title + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(banner);
      }).catch(() => {
      });
    },
    //执行删除
    handleDelete(banner){
      let url = preBannerUrl + "/" + banner.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadBannerList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBannerList();
            }
          });
        }else if(jsonResult.state == 40900){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

    },
    changeLoad(value){
      this.loadBannerList();
    },
    //翻页
    changePageNum(value){
      this.$router.replace("?pageNum="+value);
      this.loadBannerList();
    },
    //加载轮播图列表
    loadBannerList(){
      let pageNum = this.$router.currentRoute.query.pageNum;
      if(!pageNum){
        pageNum = 1;
      }
      let typeUrl = '';
      if(this.typeId != ''){
        typeUrl = '/type/' + this.typeId;
      }

      let url = preBannerUrl + typeUrl + "?pageNum="+ pageNum;
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt }})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }else if(jsonResult.state == 40100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              localStorage.removeItem("localJwt");
              this.$router.push("/login");
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadBannerList();
  }
}
</script>